const http = require('./http.js');
const config = require('./config.js');
const util = require('./util');

const GAME_ID = 14
function getLoginToken() {
    return new Promise(function (resolve, reject) {
        http.get("https://xcx-router.mingchaoyouxi.com/version_info/game_id/14/version/5").then(getdata=>{
            config.serverHost = getdata.server.backend
            config.banner_status = getdata.custom_switches[0].banner_status
            wx.login({
                success: function (res) {
                    resolve(res.code)
                },
                fail: function (err) {
                    reject(err)
                }
            })
        })

        // wx.login({
        //     success: function (res) {
        //         resolve(res.code)
        //     },
        //     fail: function (err) {
        //         reject(err)
        //     }
        // })
    })
}

/**
 * 登录
 * @param {登录返回的code} token
 * @param {通过谁分享进来的} fromOpenId
 */
function login(fromOpenId) {
    return getLoginToken().then(token => {
        let loginUrl = `/api/login.php`
        let req_body = {}
        let url = ""
        if (fromOpenId) {
            url = `${loginUrl}?game_id=${GAME_ID}&from_open_id=${fromOpenId}&token=${token}`
            req_body = {game_id: GAME_ID, token: token, from_open_id: fromOpenId}
        } else {
            url = `${loginUrl}?game_id=${GAME_ID}&token=${token}`
            req_body = {game_id: GAME_ID, token: token, from_open_id: ""}
        }
        return http.get(url, true).then(res => {
            wx.setStorageSync('mockSessionCookies', res.header['Set-Cookie'])
            console.log("login")
            console.log(res)
            console.log("login")
            return res.data
        })
    })
}

/**
 * 刷新数据
 * @param {获取运动数据返回的加密字符串} encryptedData
 * @param {获取运动数据返回的初始向量} iv
 * @param {用户名} nickName
 * @param {用户头像url} avatarUrl
 */
function refreshData(encryptedData, _iv, nickName, avatarUrl) {
    let refreshUrl = `/api/refresh.php`
    let req_body = {
        "game_id": GAME_ID,
        "encrypt_data": encryptedData,
        "iv": _iv,
        "nick_name": nickName,
        "avatar_url": avatarUrl
    }
    return http.post(refreshUrl, req_body, true).then(getData => {
        return getData
    })

}

/**
 * 新增步数
 * @param {获得步数奖励的序号}
 * @param {是否加倍}
 */
function NewAddSteps(reward_id,is_double) {
    let newAddStepUrl = "/api/get_step.php"
    let req_body = {"game_id": GAME_ID,"reward_id":parseInt(reward_id),"is_double":is_double}
    return http.post(newAddStepUrl, req_body, true).then(getData => {
        console.log("新增步数")
        console.log(getData)
        return getData
    })
}

/**
 * 步数换钱
 */
function exchange_money() {
    let exchangeUrl = "/api/exchange_money.php"
    let req_body = {"game_id": GAME_ID}
    return http.post(exchangeUrl, req_body, true).then(data => {
        console.log("步数换钱")
        console.log(data)
        console.log("步数换钱")
        return data
    })
}


/**
 * 清除数据
 * @param {获取运动数据返回的加密字符串} encryptedData
 */

function cleanData() {
    http.post("/api/gm.php", {"cmd": "clean"}).then(data => {
        console.log("清除数据返回")
        console.log(data)
    })
}

/**
 * 查询现金 by lcs
 */
function getMoney() {
    return login().then(res =>
        res.data
    )
}

/**
 * 步数明细 by lcs
 */
function getStepLog() {
    return http.get(`/api/detail.php?game_id=${GAME_ID}&type=1`).then(res => {
        console.log("getStepLog")
        console.log(res)
        console.log("getStepLog")
        return res;
    })
}

/**
 * 提现明细 by lcs
 */
function moneyLog() {
    return http.get(`/api/detail.php?game_id=${GAME_ID}&type=2`).then(res => {
        console.log("moneyLog")
        console.log(res)
        console.log("moneyLog")
        return res;
    })
}

/**
 * 提现 by lcs
 */
function withdraw(money) {
    let data = {'game_id': GAME_ID, 'take_out': money * 10000}
    return http.post(`/api/get_money.php`, data, true).then(res => {
        console.log("withdraw")
        console.log(res)
        console.log("withdraw")
        return res;
    })
}


/**
 * 领取步数奖励 by lcs
 */
function getRewardStep(appId, isDouble) {
    let data = {'game_id': GAME_ID, 'type': 2, app_id: appId, is_double: isDouble}
    return http.post(`/api/get_reward_step.php`, data, true).then(res => {
        console.log("getRewardStep")
        console.log(res)
        console.log("getRewardStep")
        return res;
    })
}

/**
 * 领取广告步数奖励 by lcs
 */

function getAdRewardStep(type,isDouble) {
    let data = {'game_id': GAME_ID, 'type': type, is_double: isDouble}
    return http.post(`/api/get_reward_step.php`, data, true).then(res => {
        console.log("getRewardStep")
        console.log(res)
        console.log("getRewardStep")
        return res;
    })
}

/**
 * 查询appIds by lcs
 */
function getJumpedAppIds() {
    return login().then(res =>
        res
    )
}

// 提供 data/table
function dataBuried(step, stepName, opendId){
  let tableName = 'log_client_loss';
  let data = {
    step: step,
    step_name: stepName,
    account_name: opendId,
    mtime: Math.round(new Date().getTime() / 1000),
    version: config.version,
    device_id: wx.getStorageSync('deviceId'),
    agent_id: 0,
    server_id: 0
  }

  let bruyData = {
    headers: {
      app_id: config.dataBuryAppId,
      log_name: tableName,
      app_key: config.dataBuryAppKey,
    },
    logs: [data]
  };

  console.log('request.js buryData--->', bruyData);
  http.dataBuried(bruyData);
}

module.exports = {
  login,
  refreshData,
  NewAddSteps,
  getMoney,
  exchange_money,
  cleanData,
  getStepLog,
  moneyLog,
  withdraw,
  getRewardStep,
  getJumpedAppIds,
  dataBuried,
  getAdRewardStep
}